// src/stores/user.js
import { defineStore } from 'pinia'

const STORAGE_TOKEN_KEY = 'token'
const STORAGE_USER_KEY = 'userInfo'

function loadStoredUser() {
  try {
    const raw = localStorage.getItem(STORAGE_USER_KEY)
    return raw ? JSON.parse(raw) : null
  } catch (error) {
    console.warn('Failed to parse cached user info, clearing it', error)
    localStorage.removeItem(STORAGE_USER_KEY)
    return null
  }
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(STORAGE_TOKEN_KEY) || '',
    info: loadStoredUser(),
    loading: false,
    error: null
  }),

  getters: {
    isLoggedIn: (state) => Boolean(state.token),
    userId: (state) => state.info?.userId ?? null,
    userName: (state) => state.info?.userName ?? '',
    roles: (state) => state.info?.roles ?? [],
    preferences: (state) => state.info?.preferences ?? []
  },

  actions: {
    setToken(token) {
      this.token = token || ''
      if (token) {
        localStorage.setItem(STORAGE_TOKEN_KEY, token)
      } else {
        localStorage.removeItem(STORAGE_TOKEN_KEY)
      }
    },

    setUserInfo(info) {
      this.info = info || null
      if (info) {
        localStorage.setItem(STORAGE_USER_KEY, JSON.stringify(info))
      } else {
        localStorage.removeItem(STORAGE_USER_KEY)
      }
    },

    setAuthState({ token, userInfo }) {
      this.setToken(token)
      this.setUserInfo(userInfo)
    },

    clearAuth() {
      this.setToken('')
      this.setUserInfo(null)
      this.error = null
    },

    setLoading(value) {
      this.loading = value
    },

    setError(message) {
      this.error = message || null
    }
  }
})
